package com.nulldev.util.security.encryptAPI.impls.aes128;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.data.Variables;
import com.nulldev.util.data.Base64.Base64;
import com.nulldev.util.security.encryptAPI.Encryptor;

public class AES128 extends Encryptor {

	private final AESCipher aes;

	public AES128(final String key) {
		this(key, true);
	}

	public AES128(final String key, final boolean padding) {
		this(key.getBytes(), padding);
	}

	public AES128(final byte[] key) {
		this(key, true);
	}

	public AES128(final byte[] key, final boolean padding) {
		super("encryptapi.legacy.aes128", new String[]
			{ "AES", "AES-128" }, key);
		if (key.length % 16 != 0)
			throw new IllegalArgumentException("Key must have a length that is a multiple of 16! [got: " + (key.length % 16) + "]");
		this.aes = new AESCipher(key, padding);
	}

	@Override
	public byte[] encryptToBytes(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return aes.getEncryptedMessage((byte[]) o);
		} else if (o instanceof String) {
			return aes.getEncryptedMessage(((String) o).getBytes());
		} else {
			throw new UnsupportedOperationException("encryptToBytes() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String encrypt(Object o) {
		Variables.notNullE(o);
		if (o instanceof byte[]) {
			return Base64.encodeBase64String(aes.getEncryptedMessage((byte[]) o));
		} else if (o instanceof String) {
			return aes.getEncryptedMessage((String) o);
		} else {
			throw new UnsupportedOperationException("encrypt() -> Unsupported operation on: " + o);
		}
	}

	@Override
	public String decrypt(String o) {
		Variables.notNullE(o);
		if (o.isEmpty())
			throw new IllegalArgumentException("o is empty!");
		return aes.getDecryptedMessage((String) o);
	}

	@Override
	public byte[] decryptToBytes(byte[] o) {
		Variables.notNullE(o);
		return aes.getDecryptedMessage(o);
	}

	@Override
	public byte[] getKey() {
		return this.key;
	}

	@Override
	public String getKeyAsString() {
		return Base64.encodeBase64String(this.key);
	}

	public static void main(String[] args) {
		final String payload = "3S3DXBuLXZ3dgp9w/4S62g==";
		final String key = "BsOKCIYGQNVKRGYtNngQwlUfRzAyXgzx";
		final AES128 aes = new AES128(key, false);
		JVM.println(new String(aes.decryptToBytes(Base64.decodeBase64(payload))));
	}

}
